﻿using Consul;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common
{
    public static class ConsulExtensions
    {
        /// <summary>
        /// 注册服务到Consul
        /// </summary>
        public static IApplicationBuilder RegisterConsul(this IApplicationBuilder app, IConfiguration config)
        {
            var consulClient = new ConsulClient(c =>
            {
                // Consul 服务器地址
                c.Address = new Uri(config["Consul:Address"] ?? "http://localhost:8500");
            });

            // 服务配置
            var serviceConfig = new AgentServiceRegistration
            {
                ID = Guid.NewGuid().ToString(), // 服务唯一ID（建议包含端口，如 user-service-5001）
                Name = config["Consul:ServiceName"], // 服务名称（如 user-service）
                Address = "localhost", // 服务IP地址（本地测试用 localhost）
                Port = int.Parse(config["Consul:ServicePort"]!), // 服务端口
                Check = new AgentServiceCheck
                {
                    // 健康检查地址（服务需实现健康检查接口）
                    HTTP = $"{config["Consul:ServiceHost"]}:{config["Consul:ServicePort"]}/api/Health/healthCheck",
                    Interval = TimeSpan.FromSeconds(10), // 检查间隔
                    Timeout = TimeSpan.FromSeconds(5), // 超时时间
                    DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(30) // 服务宕机后30秒注销
                }
            };

            // 注册服务
            consulClient.Agent.ServiceRegister(serviceConfig).Wait();

            // 应用停止时注销服务
            var lifetime = app.ApplicationServices.GetRequiredService<IHostApplicationLifetime>();
            lifetime.ApplicationStopping.Register(() =>
            {
                consulClient.Agent.ServiceDeregister(serviceConfig.ID).Wait();
            });

            return app;
        }
    }
}
